package com.tanglongan.designPattern.dp19_state.demo99;

/**
 * 状态之间自动切换版本
 */
public class GenericClient_2 {

    /**
     * 抽象状态类
     */
    static abstract class State {
        protected Context context;

        public void setContext(Context context) {
            this.context = context;
        }

        public abstract void handle();
    }

    /**
     * 具体状态A
     */
    static class ConcreteStateA extends State {
        @Override
        public void handle() {
            System.out.println("StateA do action");
            //状态A完成之后，自动切换到状态B
            this.context.setState(Context.B);
            this.context.getState().handle();
        }
    }

    /**
     * 具体状态B
     */
    static class ConcreteStateB extends State {
        @Override
        public void handle() {
            System.out.println("StateB do action");
        }
    }

    /**
     * 上下文环境
     */
    static class Context {
        private static final State A = new ConcreteStateA();
        private static final State B = new ConcreteStateB();
        //默认状态是A
        private State currentState = A;

        {
            A.setContext(this);
            B.setContext(this);
        }

        public void setState(State state) {
            this.currentState = state;
            this.currentState.setContext(this);
        }

        public State getState() {
            return this.currentState;
        }

        public void handle() {
            this.currentState.handle();
        }
    }

    public static void main(String[] args) {
        Context context = new Context();
        context.setState(new ConcreteStateA());
        context.handle();
    }
}
